var MyWebrtc = function() {
	var MediaStreamTrack = null;
	var outgoingSession = null;
	var incomingSession = null;
	var currentSession = null;
	var getJsSipgetIp = null; //存取全局IP
	var getJsSipPhoneNumber = null; //存取全局号码
	var getJsSipgetPassWord = null; //存取全局密码
	var getRemoteVideo = null;
	var getstatus1 = null;
	var getstatus2 = null;
	var globalRegisteState = '未注册';//注册状态
	var globalCallPhoneStates = "未通话";//通话状态
	var judgeIsVoice = "";//判断是语音拨打还是视频拨打
	var Datas = null;
	var localVideo = document.getElementById('selfView');
	//var remoteView = document.getElementById('remoteView');
	var selfViewWap = document.getElementById('selfViewWap');
	URL = window.URL || window.webkitURL;
	var localStream = null;
	var userAgent = null;

	//jssip实例初始化
	this.jssipAgent = function(JsSipPhoneNumber, JsSipgetIp, JsSipgetPassWord, remoteVideo, Registerstate, Callstate) {
		getJsSipPhoneNumber = JsSipPhoneNumber;
		getJsSipgetIp = JsSipgetIp;
		getJsSipgetPassWord = JsSipgetPassWord;
		getRemoteVideo = remoteVideo;
		getstatus1 = Registerstate;
		getstatus2 = Callstate;
		var phoneNumber = JsSipPhoneNumber + "@";
		var getIp = JsSipgetIp;
		getJsSipgetIp = JsSipgetIp;
		var lastPort = ":5060"
		var sip_uri_ = (phoneNumber + getIp + lastPort).toString();
		console.log(sip_uri_);
		//	var ws_uri_ = "ws://10.0.11.120:5066";
		var _Ws = "ws://";
		var _WsPort = ":5066";
		var ws_uri_ = (_Ws + getIp + _WsPort).toString();
		console.log(ws_uri_);
		//var sip_password_ = document.getElementById('JsSipgetPassWord').value;
		var sip_password_ = JsSipgetPassWord;
		console.log(sip_password_);
		//	var sip_password_ = "1234";
		var socket = new JsSIP.WebSocketInterface(ws_uri_);
		var configuration = {
			sockets: [socket],
			uri: sip_uri_,
			register: true,
			password: sip_password_,
			session_timers: false
		};

		userAgent = new JsSIP.UA(configuration);

		userAgent.on('registered', function(data) {
			console.log(data);
			console.info("registered: ", data.response.status_code, ",", data.response.reason_phrase);
			//注册状态显示
			Registerstate.innerText = "已注册";
			globalRegisteState = "已注册";
		});
		//未注册
		userAgent.on('unregistered', function(e) {
			console.log("未注册", e);
			getstatus1.innerText = "未注册";
			globalRegisteState = "未注册";
		});
		userAgent.on('registrationFailed', function(data) {
			console.log("registrationFailed, ", data);
			//注册状态显示
			Registerstate.innerText = "注册失败";
			globalRegisteState = "注册失败";
		});
		//1.在注册到期之前发射几秒钟。如果应用程序没有为这个事件设置任何监听器，JsSIP将像往常一样重新注册。
		userAgent.on('registrationExpiring', function() {

			//过期之后将自动重新注册
			console.warn("registrationExpiring");
			//重新注册
			userAgent.register();
			//jssipAgent(JsSipPhoneNumber,JsSipgetIp,JsSipgetPassWord,remoteVideo,status1,status2);
		});
		//为传入或传出的会话/呼叫而开火。
		userAgent.on('newRTCSession', function(data) {
			console.info('onNewRTCSession: ', data);
			if(data.originator == 'remote') { //incoming call
				
				//alert("请选择接听按钮");
				console.info("incomingSession, answer the call");
				incomingSession = data.session;
				Datas = data.session;
				//在这儿可以添加一个弹出对话框，选择接听或拒绝电话
							data.session.answer({
								'mediaConstraints': {
									'audio': true,
									"video": true
								},
								'mediaStream': localStream
							});
				//通话状态
				//判读语音接听方式
				console.log("judgeIsVoice",judgeIsVoice);
				Callstate.innerText = "通话中";
				globalCallPhoneStates = "通话中";
//				if (judgeIsVoice) {
//					Callstate.innerText = "语音接听";
//				globalCallPhoneStates = "语音接听";
//				getRemoteVideo.src = '';
//				}else{
//					Callstate.innerText = "视频接听";
//				globalCallPhoneStates = "视频接听";
//				}
				

			} else {
				console.info("outgoingSession");
				outgoingSession = data.session;
				outgoingSession.on('connecting', function(data) {
					//通话状态
					Callstate.innerText = "连接中";
					globalCallPhoneStates = "连接中";
					console.info('onConnecting - ', data.request);
					currentSession = outgoingSession;
					outgoingSession = null;
				});

			}
			//远程挂断事件
			data.session.on("ended", function(data) {

				console.log("call end", data);
				//通话状态
				Callstate.innerText = "已挂断";
				globalCallPhoneStates = "已挂断";
			});
			data.session.on('accepted', function(data) {
				console.info('onAccepted - ', data);
				if(data.originator == 'remote') {
					currentSession = incomingSession;
					incomingSession = null;
					console.info("setCurrentSession - ", currentSession);
					//通话状态
					getstatus2.innerText = "通话中";
					globalCallPhoneStates = "通话中";
				}
			});
			data.session.on('confirmed', function(data) {
				console.info('onConfirmed - ', data);
				if(data.originator == 'remote' && currentSession == null) {
					currentSession = incomingSession;
					incomingSession = null;
					console.info("setCurrentSession - ", currentSession);
					//通话状态
					getstatus2.innerText = "通话中";
					globalCallPhoneStates = "通话中";

				}
			});
			data.session.on('sdp', function(data) {
				console.info('onSDP, type - ', data.type, ' sdp - ', data.sdp);
				//data.sdp = data.sdp.replace('UDP/TLS/RTP/SAVPF', 'RTP/SAVPF');
				//console.info('onSDP, changed sdp - ', data.sdp);
			});
			data.session.on('progress', function(data) {
				console.info('onProgress - ', data.originator);
				if(data.originator == 'remote') {
					console.info('onProgress, response - ', data.response);
					//通话状态
					//status2.innerText = "通话中";

				}
			});
			data.session.on('peerconnection', function(data) {
				console.info('onPeerconnection - ', data.peerconnection);
				console.log(data);
				data.peerconnection.onaddstream = function(ev) {
					console.info('onaddstream from remote - ', ev);
					//remoteView.src = URL.createObjectURL(ev.stream);
					getRemoteVideo.src = window.URL && window.URL.createObjectURL(ev.stream) || ev.stream;
					getRemoteVideo.play();
				};
				
			});
		});

		console.info("call register");
		userAgent.start();
	}

	// Register callbacks to desired call events
	var eventHandlers = {
		'progress': function(e) {
			console.log('call is in progress');
			getstatus2.innerText = "连接中";
			globalCallPhoneStates = "连接中";
		},
		'failed': function(e) {
			console.log('call failed: ', e);

			if(e.cause == "Busy") {
				getstatus2.innerText = "用户正忙";
				globalCallPhoneStates = "用户正忙";
			} else {
				//通话状态
				getstatus2.innerText = "拨打失败";
				globalCallPhoneStates = "拨打失败";
				
			}
		},
		'ended': function(e) {
			//隐藏本地视频区域
			//selfViewWap.style.display = "none";
			console.log('call ended : ', e);
			//清空本地影像
			localVideo.src = "";
			//通话状态
			getstatus2.innerText = "已挂断";
			globalCallPhoneStates = "已挂断";
			
		},

		'confirmed': function(e) {
			console.log('call confirmed');
		}
	};
	//视频拨打
	this.JsSip_VideoCall = function(callPhone,isVoice) {
		
		setTimeout(function  () {
			judgeIsVoice = isVoice;//判断是语音拨打还是视频拨打
		},1000)
		console.log("judgeIsVoice",judgeIsVoice);
		//var sip_phone_number_ ="sip:1000@10.0.11.120:5060";
		var sip = "sip:";
		var getIp = getJsSipgetIp + ":5060";
		var sip_phone_number_ = (sip + callPhone + "@" + getIp).toString();
		console.log(sip_phone_number_);
		var options = {
			'eventHandlers': eventHandlers,
			'mediaConstraints': {
				'audio': true,
				'video': true,
				mandatory: {
					maxWidth: 640,
					maxHeight: 360
				}
			},

			'mediaStream': localStream
		};
		outgoingSession = userAgent.call(sip_phone_number_, options);
	}
	//调用本地视频
	this.getlocalVideo=function() {
  navigator.mediaDevices.getUserMedia({
    audio: false,
    video: true
  })
  .then(function  (stream) {
  	MediaStreamTrack = typeof stream.stop === 'function'? stream: stream.getTracks()[1];
  	localVideo.srcObject = stream;
  localStream = stream;
  })
  .catch(function(e) {
    alert('getUserMedia() error: ' + e.name);
  });
}
	//语音拨打
	this.JsSip_VoiceCall = function(callPhone,isVoice) {
		console.log("isVoice",isVoice);
		judgeIsVoice = isVoice;//判断是语音拨打还是视频拨打
		//var sip_phone_number_ ="sip:1000@10.0.11.120:5060";
		var sip = "sip:";
		var getIp = getJsSipgetIp + ":5060";
		var sip_phone_number_ = (sip + callPhone + "@" + getIp).toString();
		console.log(sip_phone_number_);
		var options = {
			'eventHandlers': eventHandlers,
			'mediaConstraints': {
				'audio': true  
			},
			'mediaStream': localStream
			
		};
		outgoingSession = userAgent.call(sip_phone_number_, options);
	}
	//语音接听
	this.VoiceAnsWter = function() {
		
		Datas.answer({
			'mediaConstraints': {
				'audio': true,
				"video": false
			},
			'mediaStream': localStream
		});
		getstatus2.innerText = "通话中";
		globalCallPhoneStates = "通话中";
	}
	//视频接听
	this.VideoAnsWter = function() {
		Datas.answer({
			'mediaConstraints': {
				'audio': true,
				"video": true
			},
			'mediaStream': localStream
		});
		//调用本地视频接口
		this.getlocalVideo();

	}
	//挂断
	this.JsSip_hangUpPhone = function() {
		//关闭本地摄像头
		//this.closeLocalCapature();
		//userAgent.stop();//保存当前的注册状态并在正常注销并终止活动会话（如果有）后断开与信令服务器的连接。
		var options = {
			all: false
		};
		userAgent.terminateSessions(options); //终止当前对话
		//通话状态
		getstatus2.innerText = "已挂断";
		globalCallPhoneStates = "已挂断";
		//清空本地影像
		localVideo.src = "";
		//当挂断电话要重新调用注册接口
		//this.jssipAgent(getJsSipPhoneNumber,getJsSipgetIp,getJsSipgetPassWord,getRemoteVideo,getstatus1,getstatus2);
	}
	//关闭本地摄像头
//	this.closeLocalCapature = function () {
//		MediaStreamTrack && MediaStreamTrack.stop();
//	}
	//注销
	this.JsSip_clearRegested = function() {
		var options = {
			all: true
		};
		userAgent.unregister(options);
		//userAgent.stop();//保存当前的注册状态并在正常注销并终止活动会话（如果有）后断开与信令服务器的连接。
	}
	//注册状态
	this.getRegisterState = function  () {
		return globalRegisteState;	
	}
	//通话状态
	this.callPoneState = function(){
		return globalCallPhoneStates;
	}
}